package com.sparrow.common.util;

import okhttp3.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {
    private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    /**
     * 发送 GET 请求
     */
    public static String get(String url, Map<String, String> headers) throws IOException {
        Request.Builder builder = new Request.Builder().url(url);
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
        Request request = builder.build();
        return executeRequest(request);
    }

    /**
     * 发送 POST 请求（JSON）
     */
    public static String post(String url, String json, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(json, JSON);
        Request.Builder builder = new Request.Builder().url(url).post(body);
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
        Request request = builder.build();
        return executeRequest(request);
    }

    /**
     * 发送 PUT 请求（JSON）
     */
    public static String put(String url, String json, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(json, JSON);
        Request.Builder builder = new Request.Builder().url(url).put(body);
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
        Request request = builder.build();
        return executeRequest(request);
    }

    /**
     * 发送 DELETE 请求
     */
    public static String delete(String url, Map<String, String> headers) throws IOException {
        Request.Builder builder = new Request.Builder().url(url).delete();
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
        Request request = builder.build();
        return executeRequest(request);
    }

    private static String executeRequest(Request request) throws IOException {
        try (Response response = CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("HTTP error code: " + response.code() + ", message: " + response.message());
            }
            ResponseBody responseBody = response.body();
            return responseBody != null ? responseBody.string() : "";
        }
    }

    public static void getAsync(String url, Map<String, String> headers, Callback callback) {
        Request.Builder builder = new Request.Builder().url(url);
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
        Request request = builder.build();
        CLIENT.newCall(request).enqueue(callback);  // 异步请求
    }

    public static void postAsync(String url, String json, Map<String, String> headers, Callback callback) {
        RequestBody body = RequestBody.create(json, JSON);
        Request.Builder builder = new Request.Builder().url(url).post(body);
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
        Request request = builder.build();
        CLIENT.newCall(request).enqueue(callback);  // 异步请求
    }


    public static void main(String[] args) {
        String json = "http://localhost:8080/?packetId=104&playerId=10000000001&orderId=ORD123456&amount=60&account=a&server=1&money=6&extData={\"type\":1,\"configId\":1}";
        try {
            String encoded = URLEncoder.encode(json, "UTF-8");
            System.out.println("原始 JSON: " + json);
            System.out.println("URL 编码后: " + encoded);

            // 可以直接拼接到 URL
            String url = "http://localhost:8080/?extData=" + encoded;
            System.out.println("完整 URL: " + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
